# This script generates Tables 5-6, Figure 2, Tables A18-23, Figures A10-A11. 


rm(list=ls())

library(modelsummary)
library(magrittr)
library(dplyr)
library(ggplot2)
library(fixest)
library(kableExtra)
library(marginaleffects)
library(here)


## Candidate-pair level data:
load(here('experimentdata_pairlevel.rda'))

## Same data but in wide format for respondents:
load(here('experimentdata_indlevel.rda'))


# Filtering those who completed too soon: outlier (1.5 times the interquartile range below the first quartile.) 

# 5 respondents are outliers:
quantile(alldata$time_min, c(0.25)) - 1.5 * IQR(alldata$time_min)

alldata %>% filter(time_min<14) %>% dplyr::select(id) %>% unique() %>% nrow()


## Two datasets for two outcomes: 

alldata_selection <- alldata %>% filter(is.na(selection)==0)

alldata_selection <- alldata_selection %>% filter(time_min>13)

## profile_order variable:
alldata_selection$last_digit_str <- as.character(alldata_selection$profile_code)

alldata_selection$profile_order <- stringi::stri_sub(alldata_selection$last_digit_str, -1)


alldata_democrat <- alldata %>% filter(is.na(democrat)==0)

alldata_democrat <- alldata_democrat %>% filter(time_min>13)

ist_subset <- ist %>% filter(time_min>13)

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

# Main Results (collapsed social policy) ----

### Selection ----

all_reg_collapsed <- feols(selection ~ law_policyRecoded*signal+ social_policyRecoded*signal, data=alldata_selection, cluster = 'id')


### Democracy rating ----

all_reg_collapsed_democ <- feols(democrat ~ law_policyRecoded*signal + social_policyRecoded*signal, data=alldata_democrat, cluster = 'id')


#### put results in a figure: 

all_effects <- slopes(all_reg_collapsed, newdata = datagrid(signal = 0:1))

all_effects_data <- all_effects[1:4, ] %>% select(term, contrast, estimate, std.error, conf.low, conf.high, signal)

all_effects_data$variables <- c('Authoritarian Candidate', 'Authoritarian Candidate', 'Democratic Candidate', 'Democratic Candidate')

all_effects_data$type <- c("No Gridlock \n Prevention", "Gridlock Prevention", 'No Corruption \n Prevention', 'Corruption Prevention')

aut_democ_fig <- ggplot(data=all_effects_data, aes(x=variables, ymin=conf.low, ymax=conf.high, y=estimate, color = type))+ geom_point(size=3, position = position_dodge(width = 0.2))+ geom_linerange(position = position_dodge(width = 0.2))+ geom_hline(aes(yintercept=0), color='grey', linewidth=1)+labs(y = "Marginal Effects of Authoritarian and Democratic Characteristics", x = "", color = 'Treatment')+theme_bw()+ theme(axis.title=element_text(size=12, face="bold"),axis.text=element_text(size=12, face="bold"), legend.position = 'bottom')+scale_color_manual(breaks = c("Corruption Prevention", "No Corruption \n Prevention", 'Gridlock Prevention', 'No Gridlock \n Prevention'),  values = c("salmon1", "brown", 'blue', 'deepskyblue'))

ggsave(aut_democ_fig, filename = here('figure2.pdf'), width = 8, height = 7)


# Results in a regression table:

modelist_collapsed <- list('Selection' = all_reg_collapsed, 'Democracy Rating' = all_reg_collapsed_democ)


modelsummary(modelist_collapsed, stars_note = TRUE, stars = c('*' = .1, '**' = .05, '***' = 0.01), gof_omit = 'DF|Deviance|AIC|BIC|F|Log.Lik.|R2 Pseudo|R2 Within|Std.Errors|RMSE', coef_map = c('law_policyRecodedjudicial_negative' = 'Authoritarian Characteristic', 'law_policyRecodedjudicial_positive' = 'Democratic Characteristic','social_policyRecodedsocial' = 'Social Policy', 'signal' = 'Version (Treatment=1)', 'law_policyRecodedjudicial_negative:signal' = 'Authoritarian Characteristic x (Treatment=1)', 'law_policyRecodedjudicial_positive:signal' = 'Democratic Characteristic x (Treatment=1)', 'social_policyRecodedsocial:signal' = 'Social Policy x (Treatment=1)', '(Intercept)'= 'Intercept'), notes = 'Standard errors are clustered at the individual level.', output = here("table_5.txt"))
             

# Main Results (not collapsed social policy) ----


### Selection ----

all_reg <- feols(selection~ law_policyRecoded+ social_policies+ law_policyRecoded*signal+ social_policies*signal, data=alldata_selection, cluster = 'id')

### Democracy rating ----

all_reg_democ <- feols(democrat~ law_policyRecoded+ social_policies+ law_policyRecoded*signal+ social_policies*signal, data=alldata_democrat, cluster = 'id')

# regression table:

modelist <- list('Selection' = all_reg, 'Democracy Rating' = all_reg_democ)

modelsummary(modelist, stars_note = TRUE, stars = c('*' = .1, '**' = .05, '***' = 0.01), gof_omit = 'DF|Deviance|AIC|BIC|F|Log.Lik.|R2 Pseudo|R2 Within|Std.Errors|RMSE', coef_map = c('law_policyRecodedjudicial_negative' = 'Authoritarian Characteristic', 'law_policyRecodedjudicial_positive' = 'Democratic Characteristic', 'social_policieseduc_food'= 'Free meal', 'social_policieseduc_lab' = 'Science lab', 'social_policieshealth_physician' = 'Attending physicians', 'social_policieshealth_sgk' = 'Social security coverage', 'signal' = 'Version (Treatment=1)', 'law_policyRecodedjudicial_negative:signal' = 'Authoritarian Characteristic x (Treatment=1)', 'law_policyRecodedjudicial_positive:signal' = 'Democratic Characteristic x (Treatment=1)', 'social_policieseduc_food:signal' = 'Free meal x (Treatment=1)', 'social_policieseduc_lab:signal' = 'Science lab x (Treatment=1)', 'social_policieshealth_physician:signal' = 'Attending physicians x (Treatment=1)', 'social_policieshealth_sgk:signal' = 'Social security coverage x (Treatment=1)', '(Intercept)'= 'Intercept'), output = here('table_A21.txt')) 


#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

# Main results heterogeneity (Erdogan vs non-erdogan voters) ----


### Selection ----

ErdoganData <- alldata_selection %>% filter(ErdoganVoters==1)
noErdoganData <- alldata_selection %>% filter(ErdoganVoters==0)


reg_erdogan <- feols(selection ~ law_policyRecoded*signal+ social_policyRecoded*signal, data=ErdoganData, cluster = 'id')

reg_No_erdogan <- feols(selection ~ law_policyRecoded*signal+ social_policyRecoded*signal, data=noErdoganData, cluster = 'id')



modelist_collapsed_erdogan <- list('Erdogan voters' = reg_erdogan, 'Non-Erdogan voters' = reg_No_erdogan)


modelsummary(modelist_collapsed_erdogan, stars_note = TRUE, stars = c('*' = .1, '**' = .05, '***' = 0.01), gof_omit = 'DF|Deviance|AIC|BIC|F|Log.Lik.|R2 Pseudo|R2 Within|Std.Errors|RMSE', coef_map = c('law_policyRecodedjudicial_negative' = 'Authoritarian Characteristic', 'law_policyRecodedjudicial_positive' = 'Democratic Characteristic', 'social_policyRecodedsocial' = 'Social Policy', 'signal' = 'Version (Treatment=1)', 'law_policyRecodedjudicial_negative:signal' = 'Authoritarian Characteristic x (Treatment=1)', 'law_policyRecodedjudicial_positive:signal' = 'Democratic Characteristic x (Treatment=1)', 'signal:social_policyRecodedsocial' = 'Social Policy x (Treatment=1)', '(Intercept)'= 'Intercept'), output = here('table_6.txt'))

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

# Gridlock concerns across parties ----


gridlockConcerns <- ist_subset %>% dplyr::select(id, a1001, a1002, a1003)
gridlockConcerns_long <- gridlockConcerns %>% tidyr::pivot_longer(a1001:a1003)

gridlockConcerns_long$variables <- ifelse(gridlockConcerns_long$name=='a1001', 'judiciary', ifelse(gridlockConcerns_long$name == 'a1002', 'legislature', 'media'))

gridlockConcerns_percentages <- gridlockConcerns_long %>% group_by(name, value) %>% summarise(count = n()) 

gridlockConcerns_percentages <- gridlockConcerns_percentages %>% filter(is.na(value)==0)

gridlockConcerns_percentages <- gridlockConcerns_percentages %>% group_by(name) %>% mutate(totalResponse = sum(count)) %>% ungroup()

gridlockConcerns_percentages$pp <- gridlockConcerns_percentages$count / gridlockConcerns_percentages$totalResponse

gridlockConcerns_percentages$variables <- ifelse(gridlockConcerns_percentages$name=='a1001', "An opposing judge prevents the government's service provision.", ifelse(gridlockConcerns_percentages$name == 'a1002', 'An opposing parliament prevents the president from working effectively.', "Opposing media try to hinder the government's services with biased news."))

gridlockConcerns_percentages$answers <- ifelse(gridlockConcerns_percentages$value==1, 'Certainly disagree', ifelse(gridlockConcerns_percentages$value==2, '2', ifelse(gridlockConcerns_percentages$value==3, 'Neither agree \n nor disagree', ifelse(gridlockConcerns_percentages$value==4, '4', ifelse(gridlockConcerns_percentages$value==5, 'Certainly agree', NA)))))

gridlockConcerns_percentages$answers <- factor(gridlockConcerns_percentages$answers, levels = c('Certainly disagree', '2', 'Neither agree \n nor disagree', '4', 'Certainly agree'))

gridlockConcerns_plot <- ggplot(data = gridlockConcerns_percentages, aes(x=answers, y = pp))+geom_bar(stat = 'identity')+ facet_wrap(~variables, ncol = 1)+theme_bw()+xlab('')+ylab('Share of respondents')


ggsave(gridlockConcerns_plot, filename = here('figure1.pdf'), height = 5, width = 5)

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@


# Explaining gridlock concerns ----

ist_subset$judiciaryobstacle <- ifelse(ist_subset$a1001 %in% c(4, 5), 1, 0)

ist_subset$legislatureobstacle <- ifelse(ist_subset$a1002 %in% c(4, 5), 1, 0)

ist_subset$mediaobstacle <- ifelse(ist_subset$a1003 %in% c(4, 5), 1, 0)


d <- ist_subset %>% dplyr::select(id, AKPvoters, educ, age, kurdish, student, housewife, religiosity, inc, hhnumber, retired, time_min, Anketor)


## seeing judiciary as an obstacle
m1 <- lm(judiciaryobstacle ~ AKPvoters+as.factor(Anketor), data = ist_subset)

m2 <- lm(judiciaryobstacle ~ AKPvoters + educ + age + kurdish+as.factor(Anketor), data = ist_subset)

m3 <- lm(judiciaryobstacle ~ AKPvoters + educ + age + kurdish + student + housewife+as.factor(Anketor), data = ist_subset)

m4 <- lm(judiciaryobstacle ~ AKPvoters + educ + age + kurdish + student + housewife + religiosity+as.factor(Anketor), data = ist_subset)

m5 <- lm(judiciaryobstacle ~ AKPvoters + educ + age + kurdish + student + housewife + religiosity+ inc+as.factor(Anketor), data = ist_subset)

## substantive effect:
mean(ist_subset$judiciaryobstacle)

## seeing legislature as obstacle
m1_legis <- lm(legislatureobstacle ~ AKPvoters+as.factor(Anketor), data = ist_subset)

m2_legis <- lm(legislatureobstacle ~ AKPvoters + educ + age + kurdish+as.factor(Anketor), data = ist_subset)

m3_legis <- lm(legislatureobstacle ~ AKPvoters + educ + age + kurdish + student + housewife+as.factor(Anketor), data = ist_subset)

m4_legis <- lm(legislatureobstacle ~ AKPvoters + educ + age + kurdish + student + housewife + religiosity+as.factor(Anketor), data = ist_subset)

m5_legis <- lm(legislatureobstacle ~ AKPvoters + educ + age + kurdish + student + housewife + religiosity+ inc+as.factor(Anketor), data = ist_subset)


## seing media as an obstacle
m1_media <- lm(mediaobstacle ~ AKPvoters+as.factor(Anketor), data = ist_subset)

m2_media <- lm(mediaobstacle ~ AKPvoters + educ + age + kurdish+as.factor(Anketor), data = ist_subset)

m3_media <- lm(mediaobstacle ~ AKPvoters + educ + age + kurdish + student + housewife+as.factor(Anketor), data = ist_subset)

m4_media <- lm(mediaobstacle ~ AKPvoters + educ + age + kurdish + student + housewife + religiosity+as.factor(Anketor), data = ist_subset)

m5_media <- lm(mediaobstacle ~ AKPvoters + educ + age + kurdish + student + housewife + religiosity+ inc+as.factor(Anketor), data = ist_subset)



models <- list('1' = m1, '2' = m3, '3' = m5, '4' = m1_legis, '5' = m3_legis, '6' = m5_legis, '7' = m1_media, '8' = m3_media, '9' = m5_media)

model_rows <- tribble(~term,  ~`1`,  ~`2`, ~`3`, ~`4`, ~`5`, ~`6`, ~`7`, ~`8`, ~`9`,
'Enumerator FE', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes')


attr(model_rows, 'position') <- c(17)

modelsummary(models, stars_note = TRUE, stars = c('*' = .1, '**' = .05, '***' = 0.01), gof_omit = 'DF|Deviance|AIC|BIC|F|Log.Lik.|R2 Pseudo|R2 Within|Std.Errors|RMSE', coef_map = c('AKPvoters' = 'AKP voters', 'educ' = 'Education level', 'age' = 'Age', 'kurdish' = 'Kurdish', 'student' = 'Student', 'housewife' = 'Housewife', 'religiosity' = 'Religiosity', 'inc' = 'Income'), add_rows = model_rows,  output = here('table_A20.txt'))


# Using "like" variable ----

alldata_like <- alldata %>% filter(time_min>13) %>% filter(is.na(like)==0)

all_reg_like <- feols(like ~ law_policyRecoded*signal+ social_policyRecoded*signal, data=alldata_like, cluster = 'id')
  

modelist_like <- list('Support' = all_reg_like)

modelsummary(modelist_like, stars_note = TRUE, stars = c('*' = .1, '**' = .05, '***' = 0.01), gof_omit = 'DF|Deviance|AIC|BIC|F|Log.Lik.|R2 Pseudo|R2 Within|Std.Errors|RMSE', coef_map = c('law_policyRecodedjudicial_negative' = 'Authoritarian Characteristic', 'law_policyRecodedjudicial_positive' = 'Democratic Characteristic','social_policyRecodedsocial' = 'Social Policy', 'signal' = 'Version (Treatment=1)', 'law_policyRecodedjudicial_negative:signal' = 'Authoritarian Characteristic x (Treatment=1)', 'law_policyRecodedjudicial_positive:signal' = 'Democratic Characteristic x (Treatment=1)', 'signal:social_policyRecodedsocial' = 'Social Policy x (Treatment=1)', '(Intercept)'= 'Intercept'), output = here('Table_A22.txt')) 

# Main results with controls -----

all_reg_controls <- feols(selection~ law_policyRecoded*signal+ social_policyRecoded*signal+ErdoganVoters+ideology+fulltime, data=alldata_selection, cluster = 'id')


modelist_controls <- list('Selection' = all_reg_controls)


rows <- tribble(~term,  ~'Selection',
                'Controls', 'Yes')


modelsummary(modelist_controls, stars_note = TRUE, stars = c('*' = .1, '**' = .05, '***' = 0.01), gof_omit = 'DF|Deviance|AIC|BIC|F|Log.Lik.|R2 Pseudo|R2 Within|Std.Errors|RMSE', coef_map = c('law_policyRecodedjudicial_negative' = 'Authoritarian Characteristic', 'law_policyRecodedjudicial_positive' = 'Democratic Characteristic','social_policyRecodedsocial' = 'Social Policy', 'signal' = 'Version (Treatment=1)', 'law_policyRecodedjudicial_negative:signal' = 'Authoritarian Characteristic x (Treatment=1)', 'law_policyRecodedjudicial_positive:signal' = 'Democratic Characteristic x (Treatment=1)', 'signal:social_policyRecodedsocial' = 'Social Policy x (Treatment=1)', '(Intercept)'= 'Intercept'),add_rows = rows, output = here('Table_A23.txt')) 


#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

# Descriptive statistics ----

important_covariates <- ist_subset %>% dplyr::select(age, female, lifesatis, demimportance, turkeydem, AKPvoters, ErdoganVoters, ideology, health, healthins, educ, kurdish, inc, religiosity, fulltime, hhnumber)

library(tidyr)

# Create a named vector for legible variable labels

variable_labels <- c(
  age = "Age",
  female = "Female",
  lifesatis = "Life Satisfaction",
  demimportance = "Democracy Importance",
  turkeydem = "Turkey Democracy",
  AKPvoters = "AKP Voters",
  ErdoganVoters = "Erdogan Voters",
  ideology = "Ideology",
  health = "Health",
  healthins = "Health Insurance",
  educ = "Education",
  kurdish = "Kurdish",
  inc = "Income",
  religiosity = "Religiosity",
  fulltime = "Full-time Employment",
  hhnumber = "Household Size"
)

# Calculate the descriptive statistics
descriptive_table <- important_covariates %>%
  summarise(across(everything(), list(
    N = ~sum(!is.na(.)),
    Mean = ~round(mean(., na.rm = TRUE), 2),
    Sd = ~round(sd(., na.rm = TRUE), 2),
    Min = ~round(min(., na.rm = TRUE), 2),
    Max = ~round(max(., na.rm = TRUE), 2)
  ))) %>%
  pivot_longer(cols = everything(), names_to = c("variable", "stat"), names_sep = "_") %>%
  pivot_wider(names_from = "stat", values_from = "value") %>%
  mutate(variable = recode(variable, !!!variable_labels)) %>%
  rename(Variable = variable)

descriptive_table <- kable( descriptive_table, format = "pipe")

# Write the descriptive table:
writeLines(descriptive_table, here('table_A18.txt'))


#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

# Balance table ----

ist_signal <- ist_subset %>% filter(signal==1)
ist_nosignal <- ist_subset %>% filter(signal==0)


# Define the variable names and their readable labels
variables <- c("age", "female", "lifesatis", "demimportance", "turkeydem", "AKPvoters", "ErdoganVoters", "ideology", "health", "healthins", "educ", "kurdish", "inc", "religiosity", "fulltime", "hhnumber")

variable_labels <- c("Age", "Female", "Life Satisfaction", "Importance of Democracy for the Respondents", "Respondents' Democracy Ratings of Turkey", "The share of AKP voters", "The share of Erdogan voters", "Ideology", "Health", "Private Health Insurance", "Education", "Kurdish", "Income", "Religiosity", "Full-Time Workers", "Household Size")

# Initialize an empty data frame for the balance table
balance_table <- data.frame(
  Variable = variable_labels,
  Treatment = numeric(length(variables)),
  Control = numeric(length(variables)),
  P_Value = numeric(length(variables))
)

# Perform t-tests for each variable and populate the table
for (i in seq_along(variables)) {
  var_name <- variables[i]
  test_result <- t.test(ist_signal[[var_name]], ist_nosignal[[var_name]])
  
  balance_table$Treatment[i] <- round(test_result$estimate[1], 3)
  balance_table$Control[i] <- round(test_result$estimate[2], 3)
  balance_table$P_Value[i] <- round(test_result$p.value, 3)
}

# Print the balance table
print(balance_table)

balance_table_result <- kable( balance_table, format = "pipe")

# Write the descriptive table:
writeLines(balance_table_result, here('table_A19.txt'))


#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

# Testing carryover effects ----

alldata_v1 <- alldata_selection %>% filter(profile_order==1)
alldata_v1_signal <- alldata_v1 %>% filter(signal==1)
alldata_v1_nosignal <- alldata_v1 %>% filter(signal==0)


alldata_v2 <- alldata_selection %>% filter(profile_order==2)
alldata_v2_signal <- alldata_v2 %>% filter(signal==1)
alldata_v2_nosignal <- alldata_v2 %>% filter(signal==0)


alldata_v3 <- alldata_selection %>% filter(profile_order==3)
alldata_v3_signal <- alldata_v3 %>% filter(signal==1)
alldata_v3_nosignal <- alldata_v3 %>% filter(signal==0)

alldata_v4 <- alldata_selection %>% filter(profile_order==4)
alldata_v4_signal <- alldata_v4 %>% filter(signal==1)
alldata_v4_nosignal <- alldata_v4 %>% filter(signal==0)

alldata_v5 <- alldata_selection %>% filter(profile_order==5)
alldata_v5_signal <- alldata_v5 %>% filter(signal==1)
alldata_v5_nosignal <- alldata_v5 %>% filter(signal==0)


all_reg1_signal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v1_signal, cluster = 'id')

all_reg1_nosignal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v1_nosignal, cluster = 'id')


all_reg2_signal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v2_signal, cluster = 'id')

all_reg2_nosignal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v2_nosignal, cluster = 'id')


all_reg3_signal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v3_signal, cluster = 'id')


all_reg3_nosignal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v3_nosignal, cluster = 'id')


all_reg4_signal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v4_signal, cluster = 'id')


all_reg4_nosignal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v4_nosignal, cluster = 'id')


all_reg5_signal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v5_signal, cluster = 'id')


all_reg5_nosignal <- feols(selection~law_policyRecoded+ social_policyRecoded, data=alldata_v5_nosignal, cluster = 'id')

# Creating a figure for easy interpretation:

coefs_signal <- data.frame(coefs= c(coef(all_reg1_signal)[[2]], coef(all_reg2_signal)[[2]], coef(all_reg3_signal)[[2]], coef(all_reg4_signal)[[2]], coef(all_reg5_signal)[[2]], coef(all_reg1_signal)[[3]], coef(all_reg2_signal)[[3]], coef(all_reg3_signal)[[3]], coef(all_reg4_signal)[[3]], coef(all_reg5_signal)[[3]], coef(all_reg1_signal)[[4]], coef(all_reg2_signal)[[4]], coef(all_reg3_signal)[[4]], coef(all_reg4_signal)[[4]], coef(all_reg5_signal)[[4]], rep(0, 5), rep(0, 5)), vars= c(rep("Autoritarian Characteristic", 5), rep("Democratic Characteristic", 5), rep("Social Policy", 5), rep("Neutral Characteristic", 5), rep("No Social Policy", 5)), profile_order=rep(1:5, 5), se = c(summary(all_reg1_signal)$se[[2]], summary(all_reg2_signal)$se[[2]], summary(all_reg3_signal)$se[[2]], summary(all_reg4_signal)$se[[2]], summary(all_reg5_signal)$se[[2]], summary(all_reg1_signal)$se[[3]], summary(all_reg2_signal)$se[[3]], summary(all_reg3_signal)$se[[3]], summary(all_reg4_signal)$se[[3]], summary(all_reg5_signal)$se[[3]], summary(all_reg1_signal)$se[[4]], summary(all_reg2_signal)$se[[4]], summary(all_reg3_signal)$se[[4]], summary(all_reg4_signal)$se[[4]], summary(all_reg5_signal)$se[[4]], rep(0, 5), rep(0, 5)))  

coefs_signal$lo95 <- coefs_signal$coefs-1.96*coefs_signal$se
coefs_signal$hi95 <- coefs_signal$coefs+1.96*coefs_signal$se


coefs_signal$vars <- factor(coefs_signal$vars, level=c("Social Policy", "No Social Policy", "Neutral Characteristic", "Democratic Characteristic", "Autoritarian Characteristic"))



labelcolors <- ifelse(levels(coefs_signal$vars) == "No Social Policy" | levels(coefs_signal$vars)=="Social Policy", "blue", "black")

plot_signal <- ggplot(coefs_signal, aes(x=vars, y=coefs, ymin=lo95, ymax=hi95))+geom_linerange(size=0.8)+geom_point(size=1.6)+ geom_hline(aes(yintercept=0), color='red', linetype=2)+ facet_grid(profile_order ~ .)+ylab("Change: Pr(Prefer Candidate for President)")+xlab("")+ theme(axis.text.x = element_text(angle = 45, hjust = 1))+ coord_flip()+theme_bw()+ theme(axis.text.y = element_text(colour=labelcolors))


ggsave(plot_signal, filename = here('figure_A10.pdf'), width = 5, height = 5)

# Same for the control group

coefs_nosignal <- data.frame(coefs= c(coef(all_reg1_nosignal)[[2]], coef(all_reg2_nosignal)[[2]], coef(all_reg3_nosignal)[[2]], coef(all_reg4_nosignal)[[2]], coef(all_reg5_nosignal)[[2]], coef(all_reg1_nosignal)[[3]], coef(all_reg2_nosignal)[[3]], coef(all_reg3_nosignal)[[3]], coef(all_reg4_nosignal)[[3]], coef(all_reg5_nosignal)[[3]], coef(all_reg1_nosignal)[[4]], coef(all_reg2_nosignal)[[4]], coef(all_reg3_nosignal)[[4]], coef(all_reg4_nosignal)[[4]], coef(all_reg5_nosignal)[[4]], rep(0, 5), rep(0, 5)), vars= c(rep("Autoritarian Characteristic", 5), rep("Democratic Characteristic", 5), rep("Social Policy", 5), rep("Neutral Characteristic", 5), rep("No Social Policy", 5)), profile_order=rep(1:5, 5), se = c(summary(all_reg1_nosignal)$se[[2]], summary(all_reg2_nosignal)$se[[2]], summary(all_reg3_nosignal)$se[[2]], summary(all_reg4_nosignal)$se[[2]], summary(all_reg5_nosignal)$se[[2]], summary(all_reg1_nosignal)$se[[3]], summary(all_reg2_nosignal)$se[[3]], summary(all_reg3_nosignal)$se[[3]], summary(all_reg4_nosignal)$se[[3]], summary(all_reg5_nosignal)$se[[3]], summary(all_reg1_nosignal)$se[[4]], summary(all_reg2_nosignal)$se[[4]], summary(all_reg3_nosignal)$se[[4]], summary(all_reg4_nosignal)$se[[4]], summary(all_reg5_nosignal)$se[[4]], rep(0, 5), rep(0, 5)))  

coefs_nosignal$lo95 <- coefs_nosignal$coefs-1.96*coefs_nosignal$se
coefs_nosignal$hi95 <- coefs_nosignal$coefs+1.96*coefs_nosignal$se


coefs_nosignal$vars <- factor(coefs_nosignal$vars, level=c("Social Policy", "No Social Policy", "Neutral Characteristic", "Democratic Characteristic", "Autoritarian Characteristic"))


labelcolors <- ifelse(levels(coefs_nosignal$vars) == "No Social Policy" | levels(coefs_nosignal$vars)=="Social Policy", "blue", "black")

plot_nosignal <- ggplot(coefs_nosignal, aes(x=vars, y=coefs, ymin=lo95, ymax=hi95))+geom_linerange(size=0.8)+geom_point(size=1.6)+ geom_hline(aes(yintercept=0), color='red', linetype=2)+ facet_grid(profile_order ~ .)+ylab("Change: Pr(Prefer Candidate for President)")+xlab("")+ theme(axis.text.x = element_text(angle = 45, hjust = 1))+ coord_flip()+theme_bw()+ theme(axis.text.y = element_text(colour=labelcolors))

ggsave(plot_nosignal, filename = here('figure_A11.pdf'), width = 5, height = 5)


#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@


sample_signal <- alldata_selection %>% filter(signal==1)
sample_nosignal <- alldata_selection %>% filter(signal==0)


carryover_test_lm1 <- feols(selection~law_policyRecoded + profile_order+law_policyRecoded:profile_order, data=sample_signal, cluster = 'id')


## Wald tests for caryover effects: 

## Testing the null hypothesis that the effect of law policy is identical across tasks. Failure to reject this means: no caryover effect!

wald(carryover_test_lm1, c('law_policyRecodedjudicial_negative:profile_order2', 'law_policyRecodedjudicial_negative:profile_order3', 'law_policyRecodedjudicial_negative:profile_order4', 'law_policyRecodedjudicial_negative:profile_order5', 'law_policyRecodedjudicial_positive:profile_order2', 'law_policyRecodedjudicial_positive:profile_order3', 'law_policyRecodedjudicial_positive:profile_order4', 'law_policyRecodedjudicial_positive:profile_order5'))


## in no signal sample
carryover_test_lm_nosignal <- feols(selection~law_policyRecoded + profile_order+law_policyRecoded:profile_order, data=sample_nosignal, cluster = 'id')


##Testing the null hypothesis that the effect of law policy is identical across tasks. Failure to reject this means: no caryover effect!

wald(carryover_test_lm_nosignal, c('law_policyRecodedjudicial_negative:profile_order2', 'law_policyRecodedjudicial_negative:profile_order3', 'law_policyRecodedjudicial_negative:profile_order4', 'law_policyRecodedjudicial_negative:profile_order5', 'law_policyRecodedjudicial_positive:profile_order2', 'law_policyRecodedjudicial_positive:profile_order3', 'law_policyRecodedjudicial_positive:profile_order4', 'law_policyRecodedjudicial_positive:profile_order5'))



# Testing profile order effect ----
sample_signal$candidate <- as.factor(sample_signal$candidate)

profile_order_lm_signal <- feols(selection~law_policyRecoded+candidate+law_policyRecoded:candidate, data=sample_signal, cluster = 'id')

##Testing the null hypothesis that the effect of law policy is identical across tasks. Failure to reject this means: no profile order effect!
wald(profile_order_lm_signal, c('law_policyRecodedjudicial_negative:candidateB', 'law_policyRecodedjudicial_positive:candidateB'))


##Sample with No signal
sample_nosignal$candidate <- as.factor(sample_nosignal$candidate)

profile_order_lm <- feols(selection~law_policyRecoded+candidate+law_policyRecoded:candidate, data=sample_nosignal, cluster = 'id')


wald(profile_order_lm, c('law_policyRecodedjudicial_negative:candidateB', 'law_policyRecodedjudicial_positive:candidateB'))


